package com.chungkui.check.expression.impl;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.BaseExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import com.chungkui.check.util.JsonUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author jason
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class JsonExpression extends BaseExpression {
    private String param;
    private String code;
    private Boolean require;

    @Override
    public CheckResult match(Map<String, Object> params) {
        String val = MapUtils.getString(params, this.param);
        if (require != null && require && StringUtils.isBlank(val)) {
            return CheckResult.fail(this.code, this.param, MapUtils.getString(this.msg, Constants.NULL, normalMsg), val);
        }
        if (StringUtils.isNotEmpty(val)) {
            Map<String, Object> data = JsonUtil.json2map(val);
            if (data == null) {
                return CheckResult.fail(this.code, this.param, MapUtils.getString(this.msg, Constants.FAIL, normalMsg), val);
            }
        }
        return CheckResult.success();

    }

    @Override
    public void compile(Map<String, Object> config) {
        this.param = MapUtils.getString(config, "param");
        this.code = MapUtils.getString(config, "code");
       /* Object msgConfig = MapUtils.getObject(config,  Constants.MSG);
        if (msgConfig instanceof String) {
            this.normalMsg = (String) msgConfig;
        } else if(msgConfig instanceof Map){
            this.msg = (Map<String, Object>) msgConfig;
        }*/
        this.require = MapUtils.getBoolean(config, "require", true);
    }

    @Override
    public InsideType getInsideType() {
        return InsideType.JSON_OBJECT;
    }
}
